<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { useImage } from '@/hooks';
import { useRouterPush } from '@/composables';
import { useNurseGoods } from '@/service';
import { hideLoading, showLoading } from '@tarojs/taro';
import good from './good.vue';
import { getDict } from '@/service/api/dict';
const props = defineProps({
    hospital: {
        type: String,
        required: true
    }
});

const list = ref<any>([]);

const { getGoodsList, loadTreeChildrenNew } = useNurseGoods();

const modelValue = ref('2');

const select = ref('');

const act3 = ref('');
const productList = ref<any[]>([]);
const typeList = ref<any[]>([]);

onMounted(() => {
    getDict("nurse_type").then((res:any) => {
        console.log("res==== nurse type", res)
        typeList.value = res;
    })
    
    // 添加调试信息
    console.log('tabs.vue onMounted - list.value:', list.value);
    console.log('tabs.vue onMounted - list.value?.length:', list.value?.length);
    
    // 延迟检查数据
    setTimeout(() => {
        console.log('tabs.vue delayed check - list.value:', list.value);
        console.log('tabs.vue delayed check - list.value?.length:', list.value?.length);
    }, 1000);
})

const selectSonCategory = (id: string) => {
    act3.value = id;
    getSonCategory()
};

const { toGoodsDetail } = useRouterPush();

const toDetail = (item: any) => {
    console.log('toDetail', item);
    toGoodsDetail({
        id: item.id,
        pic: item.pic,
        pname: item.goods_name,
        unit: item.unit,
        nurseType: modelValue.value,
        goods_type: '1',
        nurseTypeText: item.goods_name
    });
};

const getData = async () => {
    showLoading({ title: '正在请求...' });
    const { error, success } = await getGoodsList({
        pid: '0',
        nurse_type: modelValue.value,
        hospital: props.hospital
    });
    console.log('success $$$$$$$', success);
    if (!error && success) list.value = success;

    list.value.forEach(async (item: any, index: number) => {
        const { error: detailError, success: data } = await loadTreeChildrenNew({ pid: item.key });
        if (!detailError && data) item.children = data;
        if (index === 0) selectSonCategory(item.children[0].id);
    });
    if (list?.value?.length > 0) select.value = list?.value[0].key;

    // 添加调试信息
    console.log('getData - list.value:', list.value);
    console.log('getData - list.value?.length:', list.value?.length);
    console.log('getData - select.value:', select.value);

    hideLoading();
};

async function getSonCategory() {
    // return item.children.find((item: any) => item.id === act3.value);
    const res = await loadTreeChildrenNew({ pid: act3.value });
    console.log('res ---->', res);
    productList.value = res.success || [];
}

watch(
    () => [modelValue.value],
    () => {
        console.log("modelValue.value ===", modelValue.value)
        getData();
    }
);

// 监听list变化
watch(
    () => list.value,
    (newList) => {
        console.log("list.value changed:", newList);
        console.log("list.value.length:", newList?.length);
        if (newList?.length > 0) {
            console.log("Setting select to:", newList[0].key);
            select.value = newList[0].key;
        }
    },
    { deep: true }
);

// 监听select变化
watch(
    () => select.value,
    (newSelect) => {
        console.log("select.value changed:", newSelect);
    }
);

// 暴露验证方法给父组件
defineExpose({
    getData: () => getData(),
    // 添加测试滚动功能的方法
    testScroll: () => {
        console.log('Testing scroll functionality...');
        console.log('Current list length:', list.value?.length);
        console.log('Current select value:', select.value);
        
        // 模拟添加更多数据来测试滚动
        if (list.value?.length > 0) {
            const testItems = Array.from({ length: 20 }, (_, i) => ({
                key: `test-${i}`,
                title: `测试项目 ${i + 1}`,
                has_child: 0,
                children: []
            }));
            
            console.log('Adding test items for scroll testing...');
            list.value = [...list.value, ...testItems];
        }
    }
});

function hasChildren(list: any) {
    // if (list?.length > 0) {
    //     return list[0].has_child === 1;
    // }
    return list.has_child == 1;
    // return false;
}
</script>

<template>
    <view class="h-full w-full flex flex-col">
        <nut-tabs v-model="modelValue" title-scroll title-gutter="20" size="large" background="#fff" class="w-full h-40px bg-#fff flex-shrink-0">
            <nut-tab-pane :title="item.itemText" :pane-key="item.itemValue" v-for="item in typeList" :key="item.id"></nut-tab-pane>
        </nut-tabs>
        
        <view class="w-full flex-1 flex overflow-hidden">
            <nut-empty v-if="!list || list.length == 0" description="暂无数据" class="flex-1"></nut-empty>
            <view v-else class="flex-1 flex">
                <!-- 左侧导航 -->
                <scroll-view class="nav-scroll-view" scroll-y="true" show-scrollbar="true" enhanced="true">
                    <view class="nav-container">
                        <view 
                            v-for="item in list" 
                            :key="item.key" 
                            class="nav-item"
                            :class="select === item.key ? 'active' : ''"
                            @tap="select = item.key"
                        >
                            {{ item.title }}
                        </view>
                    </view>
                </scroll-view>
                
                <!-- 右侧内容 -->
                <scroll-view class="content-scroll-view" scroll-y="true" show-scrollbar="true" enhanced="true">
                    <view class="content-container">
                        <view v-for="item in list" :key="item.key" v-show="select === item.key">
                            <template v-if="hasChildren(item)">
                                <view class="mb-[30rpx] p-[20rpx]">
                                    <!-- 三级分类 -->
                                    <nut-button class="text-[32rpx] inline-block mr-[20rpx] mb-[20rpx]"
                                    v-for="sonCategory in item.children"
                                    :type="act3 === sonCategory.id?'success':'default'"
                                    plain
                                    :key="sonCategory.id"
                                    size="small"
                                    @tap="selectSonCategory(sonCategory.id)"
                                    >{{ sonCategory.type_name }}</nut-button>
                                </view>
                                <view class="p-[20rpx]">
                                    <good v-for="item2 in productList" :key="item2.id" :obj="item2" :src="useImage(item2.pic)"
                                        @jump="toDetail(item2)" />
                                </view>
                            </template>
                            <template v-else>
                                <view class="p-[20rpx]">
                                    <good v-for="item2 in item.children" :key="item2.id" :obj="item2" :src="useImage(item2.pic)"
                                        @jump="toDetail(item2)" />
                                </view>
                            </template>
                        </view>
                    </view>
                </scroll-view>
            </view>
        </view>
    </view>
</template>

<style lang="scss" >
.nut-tabs__titles-item {
    width: fit-content !important;
}

/* 左侧导航滚动区域 */
.nav-scroll-view {
    width: 200rpx;
    height: 100%;
    background-color: #f9fafb;
    border-right: 1px solid #e5e7eb;
    flex-shrink: 0;
    overflow: hidden;
}

.nav-container {
    width: 100%;
    min-height: 100%;
    padding-bottom: 20rpx;
    box-sizing: border-box;
}

/* 左侧导航项样式 */
.nav-item {
    width: 100%;
    padding: 20rpx 30rpx;
    font-size: 28rpx;
    border-bottom: 1px solid #f3f4f6;
    background-color: #f9fafb;
    color: #374151;
    cursor: pointer;
    transition: all 0.3s ease;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    box-sizing: border-box;
    min-height: 60rpx;
    display: flex;
    align-items: center;
    flex-shrink: 0;
}

.nav-item:hover {
    background-color: #f3f4f6;
}

.nav-item.active {
    background-color: #ffffff;
    color: #3b82f6;
    font-weight: 500;
    border-right: 3px solid #3b82f6;
}

/* 右侧内容滚动区域 */
.content-scroll-view {
    flex: 1;
    height: 100%;
    background-color: #ffffff;
    overflow: hidden;
}

.content-container {
    width: 100%;
    min-height: 100%;
    padding: 10rpx;
    box-sizing: border-box;
}

/* 滚动条样式 */
.nav-scroll-view::-webkit-scrollbar,
.content-scroll-view::-webkit-scrollbar {
    width: 6rpx;
}

.nav-scroll-view::-webkit-scrollbar-track,
.content-scroll-view::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3rpx;
}

.nav-scroll-view::-webkit-scrollbar-thumb,
.content-scroll-view::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3rpx;
}

.nav-scroll-view::-webkit-scrollbar-thumb:hover,
.content-scroll-view::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

/* 确保内容区域可以滚动 */
.content-container > view {
    width: 100%;
    min-height: 100%;
}
</style>
